import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 * 
 */

/**
 * @author hck
 *
 */
public class AnalyseHrData {
	
	static String m_sTacxExportedHeartRateFile = "tacx_hear_rate_file.hrm";
    static String m_sHrDataSectionName="HRData";
    static boolean m_bInsideHearRateDataSection=false;

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		BufferedReader cHrmBuffer;
		String sDelimiter="\t";
		//String sDelimiter=" +";
		// TODO N make the tmpdata dir a parameter that can be configured.
		String sDataOutputFileName="tmpdata/bike_data.csv";
		int nHrDataLineCount=0;
		
		try {
			System.out.println("GenerateDataFile(" + sDataOutputFileName + ")");
            FileWriter file = new FileWriter(sDataOutputFileName);
            BufferedWriter cDataOutputStream = new BufferedWriter(file);
            // TODO V Make the line work on both Linux and Windows (Handle the '\n' better).
            cDataOutputStream.write("#HR, Speed, Cadence, Watt\n");

			cHrmBuffer = new BufferedReader(new FileReader(m_sTacxExportedHeartRateFile));
	    String sLineRead;
	    // TODO N Get 'Interval' from the 'Params' section.
	    while ((sLineRead = cHrmBuffer.readLine()) != null) {
			if ( (sLineRead.contains("[")) && ( sLineRead.contains("]"))) {
				m_bInsideHearRateDataSection = false;
	        }
			// TODO N identify empty line and set to m_bInsideHearRateDataSection false. 
			if ( m_bInsideHearRateDataSection )  {
				
				nHrDataLineCount++;
				String sTemp[] = sLineRead.split(sDelimiter);
				
				
				/*
				System.out.print("Pulse:");
				System.out.print(sTemp[0]);
				System.out.print("  ");
		        System.out.println(sLineRead);	  
		        */
				if (sTemp.length==5) {
				  cDataOutputStream.write(String.format("%s, %s, %s, %s", sTemp[0], sTemp[1], sTemp[2], sTemp[4]));
				  cDataOutputStream.write("\n");
				}
			}
			if ( sLineRead.contains(m_sHrDataSectionName)) {
				m_bInsideHearRateDataSection = true;
	        }
	    }
	    cHrmBuffer.close();
	    System.out.printf("Total HR Data Lines:%d\n", nHrDataLineCount);
        cDataOutputStream.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
